﻿using System;
using System.Collections.Generic;
using System.Linq;
using FineUI;
using SysManage.BLL;
using ZHDJ.Data.Models.Common;
using ZHDJ.Data.Models.Edu;

namespace SysManage.Module.Menu
{
    public partial class PartyModuleNavigationList : PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyModuleNavigationView";
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdSelectrowindex.Text = "0";
                LoadData();
            }

        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton("PartyModuleNavigationAdd", btnNew);
            CheckPowerWithButton("PartyModuleNavigationDelete", btnDeleteSelected);

            BindGrid1();


           
            btnModule.OnClientClick = WindowModule.GetShowReference("~/app/SysManage/Module/Menu/PartyModuleNavigationModuleEdit.aspx");
            // 每页记录数
            Grid2.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();
            BindGrid2();
        }

        private void BindGrid1()
        {
            IQueryable<PartyModuleNavigation> q = DB.PartyModuleNavigations;
            q = q.Where(a => string.IsNullOrEmpty(a.Category));
            // 排列
            q = Sort<PartyModuleNavigation>(q, Grid1);


            Grid1.DataSource = q;
            Grid1.DataBind();
            if (string.IsNullOrEmpty(this.hdModule.Text))
            {
                hdSelectrowindex.Text = "0";
                // 默认选中第一个
                Grid1.SelectedRowIndex = 0;
                this.hdModule.Text= GetSelectedDataKeyID(Grid1);
            }
            else
            {
                SetSelectedDataKeyIDs(Grid1, this.hdModule.Text);
                hdSelectrowindex.Text = Grid1.SelectedRowIndex.ToString();
            }
            PageContext.RegisterStartupScript("addSelectCss(" + this.hdSelectrowindex.Text + ")");

        }

        private void BindGrid2()
        {
            string modulelID = hdModule.Text;
            

            if (string.IsNullOrEmpty(hdModule.Text))
            {
                Grid2.RecordCount = 0;

                Grid2.DataSource = null;
                Grid2.DataBind();
            }
            else
            {
                btnNew.OnClientClick = Window1.GetShowReference("~/app/SysManage/Module/Menu/PartyModuleNavigationEdit.aspx?module=" + modulelID);

                IQueryable<PartyModuleNavigation> q = DB.PartyModuleNavigations;

                // 搜索内容
                string searchText = ttbSearchUser.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q = q.Where(u => u.PageName.Contains(searchText) && u.Module == modulelID && !string.IsNullOrEmpty(u.Category));
                }
                else
                {
                    q = q.Where(u => u.Module == modulelID && !string.IsNullOrEmpty(u.Category));
                }
                // 过滤启用状态
                if (rblEnableStatus.SelectedValue != "all")
                {
                    q = q.Where(u => u.Enabled == (rblEnableStatus.SelectedValue == "enabled" ? true : false));
                }
                // 在查询添加之后，排序和分页之前获取总记录数
                Grid2.RecordCount = q.Count();

                // 排列和分页
                q = SortAndPage<PartyModuleNavigation>(q, Grid2);

                Grid2.DataSource = q;
                Grid2.DataBind();
            }

        }


        #endregion

        #region Events

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid2.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);

            BindGrid2();
        }


        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid1();

            // 默认选中第一个职称
            Grid1.SelectedRowIndex = 0;

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            string module = GetSelectedDataKeyID(Grid1);
            this.hdModule.Text = module;
           
            this.hdSelectrowindex.Text = Grid1.SelectedRowIndex.ToString();
            PageContext.RegisterStartupScript("addSelectCss(" + this.hdSelectrowindex.Text + ")");
            btnNew.OnClientClick = Window1.GetShowReference("~/app/SysManage/Module/Edu/PartyModuleNavigationEdit.aspx?module=" + module, "新增");
            BindGrid2();
           
               
            
        }

        #endregion

        #region Grid2 Events
        protected void Grid2_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithLinkButtonField("PartyModuleNavigationDelete", Grid2, "deleteField");
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortDirection = e.SortDirection;
            Grid2.SortField = e.SortField;
            BindGrid2();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid2();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyModuleNavigationDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            List<string> ids = GetSelectedDataKeyIDs(Grid2);
            DB.PartyModuleNavigations.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyModuleNavigations.Remove(u));
            DB.SaveChanges();

            // 清空当前选中的项
            Grid2.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid2();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid2();
        }

        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid2.DataKeys[e.RowIndex];
            string ID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                var del = DB.PartyModuleNavigations.FirstOrDefault(t => t.ID == ID);
                DB.PartyModuleNavigations.Remove(del);
                DB.SaveChanges();
                BindGrid2();

            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid1.DataKeys[e.RowIndex];
            string ID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                var del = DB.PartyModuleNavigations.FirstOrDefault(t => t.ID == ID);
                DB.PartyModuleNavigations.Remove(del);
                DB.SaveChanges();
                LoadData();

            }
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="enabled"></param>
        private void SetSelectedEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyModuleNavigationEdit"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid2);

            // 执行数据库操作
            DB.PartyModuleNavigations.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => u.Enabled = enabled);
            DB.SaveChanges();
            //DB.Users.Update(u => ids.Contains(u.ID), u => new User { Enabled = enabled });

            // 重新绑定表格
            BindGrid2();
        }
        protected void btnEnable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(true);
        }

        protected void btnDisable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(false);
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
           
            BindGrid2();
        }
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            //this.hdModule.Text = "";
            BindGrid1();

            BindGrid2();          
        }
        #endregion        
    }
}
